package com.shop.shopserver.service.impl;

import com.shop.shoppojo.entity.HotSearch;
import com.shop.shopserver.mapper.HotSearchMapper;
import com.shop.shopserver.service.HotSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HotSearchServiceImpl implements HotSearchService {
    @Autowired
    private HotSearchMapper hotSearchMapper;

    @Override
    public List<HotSearch> getRandomHotSearches(int num) {
        List<HotSearch> allHotSearches = hotSearchMapper.findAllHotSearches();
        if (allHotSearches.isEmpty()) {
            return new ArrayList<>();
        }
        Random random = new Random();
        List<HotSearch> randomHotSearches = new ArrayList<>();
        Set<Integer> usedIndices = new HashSet<>(); // 用于存储已经使用过的索引
        while (randomHotSearches.size() < num && usedIndices.size() < allHotSearches.size()) {
            //生成一个随机整数，作为从 allHotSearches 列表中选取元素的索引，确保生成的随机索引在 allHotSearches 列表的有效索引范围内
            int randomIndex = random.nextInt(allHotSearches.size());
            //检查 usedIndices 集合中是否已经包含了当前生成的随机索引 randomIndex
            if (!usedIndices.contains(randomIndex)) {
                //如果上述条件为真，即当前随机索引还没有被使用过，就将这个索引添加到 usedIndices 集合中，用于记录已经使用过这个索引
                usedIndices.add(randomIndex);
                randomHotSearches.add(allHotSearches.get(randomIndex));
            }
        }
        return randomHotSearches;
    }

}
